class WebSocketClient {
    constructor(url) {
        this.url = url;
        this.client = null;
        this.reconnectInterval = 5000;
        this.shouldReconnect = true;
    }

    connect() {
        this.client = new WebSocket(this.url);

        this.client.onopen = () => {
            console.log('WebSocket connected');
            this.authenticate();
        };

        this.client.onmessage = (event) => {
            this.handleMessage(JSON.parse(event.data));
        };

        this.client.onclose = () => {
            console.log('WebSocket disconnected');
            if (this.shouldReconnect) {
                setTimeout(() => this.connect(), this.reconnectInterval);
            }
        };
    }

    authenticate() {
        const token = Dcat.token;
        this.send({
            type: 'auth',
            token: token
        });
    }

    send(data) {
        if (this.client.readyState === WebSocket.OPEN) {
            this.client.send(JSON.stringify(data));
        }
    }

    handleMessage(data) {
        switch (data.type) {
            case 'notification':
                this.showNotification(data);
                break;
            case 'reload':
                Dcat.reload();
                break;
            case 'redirect':
                window.location.href = data.url;
                break;
        }
    }

    showNotification(data) {
        Dcat.success(data.message, data.title || '通知');
    }
}

// 初始化连接
const wsClient = new WebSocketClient(`ws://${window.location.hostname}:9502`);
wsClient.connect();
